package com.teradata.params.core.shiro.factroy;

import com.teradata.params.core.constant.ConstantFactory;
import com.teradata.params.core.constant.state.ManagerStatus;
import com.teradata.params.core.model.App;
import com.teradata.params.core.shiro.ShiroApp;
import com.teradata.params.system.dao.MenuDao;
import com.teradata.params.system.dao.AppMgrDao;
import com.teradata.params.util.Convert;
import com.teradata.params.util.SpringContextHolder;
import org.apache.shiro.authc.CredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
@DependsOn("springContextHolder")
@Transactional(readOnly = true)
public class ShiroFactroy implements IShiro {

    @Autowired
    private AppMgrDao appMgrDao;

    @Autowired
    private MenuDao menuDao;

    public static IShiro me() {
        return SpringContextHolder.getBean(IShiro.class);
    }


    @Override
    public App app(String appId) {
        App app = appMgrDao.getByAppId(appId);
        // 账号不存在
        if (null == app) {
            throw new CredentialsException();
        }
        // 账号被冻结
        if (app.getStatus() != ManagerStatus.OK.getCode()) {
            throw new LockedAccountException();
        }
        return app;
    }

    @Override
    public ShiroApp shiroApp(App app) {
        ShiroApp shiroApp = new ShiroApp();

        shiroApp.setAppId(app.getAppId());
        shiroApp.setAppName(app.getAppName());
        shiroApp.setAppKey(app.getAppKey());
        shiroApp.setRegeditTime(app.getRegeditTime());
        shiroApp.setStatus(app.getStatus());

        shiroApp.setDeptName(ConstantFactory.me().getDeptName(app.getDeptid()));

        Integer[] roleArray = Convert.toIntArray(app.getRoleid());
        List<Integer> roleList = new ArrayList<Integer>();
        List<String> roleNameList = new ArrayList<String>();
        for (int roleId : roleArray) {
            roleList.add(roleId);
            roleNameList.add(ConstantFactory.me().getSingleRoleName(roleId));
        }
        shiroApp.setRoleList(roleList);
        shiroApp.setRoleNames(roleNameList);

        return shiroApp;
    }

    @Override
    public List<String> findPermissionsByRoleId(Integer roleId) {
        List<String> resUrls = menuDao.getResUrlsByRoleId(roleId);
        return resUrls;
    }

    @Override
    public String findRoleNameByRoleId(Integer roleId) {
        return null;
    }

    @Override
    public SimpleAuthenticationInfo info(ShiroApp shiroApp, App app, String realmName) {
        return null;
    }
}
